<template>
  <div class="app-container">
    <!-- 头部信息 -->
    <el-card class="header-card">
      <div class="header-content">
        <div class="header-left">
          <h2 class="page-title">退料入库</h2>
          <div class="task-info">
            <span>任务编号：{{ taskInfo.taskCode }}</span>
            <span style="margin-left: 20px;">工单编号：{{ taskInfo.workOrderCode }}</span>
            <span style="margin-left: 20px;">创建时间：{{ currentTime }}</span>
          </div>
        </div>
        <div class="header-right">
          <el-button @click="goBack">返回</el-button>
        </div>
      </div>
    </el-card>

    <!-- 主要内容 -->
    <el-card class="content-card">
      <div class="content-header">
        <h3>物料退料单</h3>
        <div class="form-actions">
          <el-button type="primary" @click="handleSubmit" :loading="submitting">提交退料</el-button>
          <el-button @click="handleSaveDraft">保存草稿</el-button>
          <el-button @click="handleReset">重置</el-button>
        </div>
      </div>

      <!-- 基础信息表单 -->
      <el-form ref="returnForm" :model="returnForm" :rules="formRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="退料单号" prop="returnCode">
              <el-input v-model="returnForm.returnCode" placeholder="系统自动生成" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="退料类型" prop="returnType">
              <el-select v-model="returnForm.returnType" placeholder="请选择退料类型" style="width: 100%;">
                <el-option label="生产退料" value="production" />
                <el-option label="质量问题退料" value="quality" />
                <el-option label="其他退料" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="退料日期" prop="returnDate">
              <el-date-picker
                v-model="returnForm.returnDate"
                type="date"
                placeholder="选择退料日期"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="退料仓库" prop="warehouseId">
              <el-select v-model="returnForm.warehouseId" placeholder="请选择仓库" style="width: 100%;" @change="handleWarehouseChange">
                <el-option
                  v-for="warehouse in warehouseList"
                  :key="warehouse.warehouseId"
                  :label="warehouse.warehouseName"
                  :value="warehouse.warehouseId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="退料人" prop="returner">
              <el-input v-model="returnForm.returner" placeholder="请输入退料人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="退料部门" prop="department">
              <el-input v-model="returnForm.department" placeholder="请输入退料部门" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="退料原因" prop="returnReason">
              <el-select v-model="returnForm.returnReason" placeholder="请选择退料原因" style="width: 100%;">
                <el-option label="生产任务完成，剩余物料退回" value="task_complete" />
                <el-option label="物料质量问题" value="quality_issue" />
                <el-option label="物料规格不符" value="spec_mismatch" />
                <el-option label="生产计划变更" value="plan_change" />
                <el-option label="其他原因" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="returnForm.remark" type="textarea" :rows="3" placeholder="请输入详细的退料说明" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 物料明细 -->
      <div class="material-section">
        <div class="section-header">
          <h4>退料明细</h4>
          <el-button type="primary" size="small" @click="handleAddMaterial">添加物料</el-button>
        </div>
        
        <el-table :data="materialList" style="width: 100%;" border>
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column label="物料编号" prop="materialCode" width="150" align="center">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.materialCode"
                placeholder="请选择物料"
                filterable
                @change="handleMaterialChange(scope.$index, scope.row)"
                style="width: 100%;"
              >
                <el-option
                  v-for="material in usedMaterials"
                  :key="material.materialCode"
                  :label="material.materialCode"
                  :value="material.materialCode"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" prop="materialName" width="200" align="center" />
          <el-table-column label="规格型号" prop="specification" width="150" align="center" />
          <el-table-column label="单位" prop="unit" width="80" align="center" />
          <el-table-column label="已领用数量" prop="usedQty" width="100" align="center" />
          <el-table-column label="可退料数量" prop="availableQty" width="100" align="center" />
          <el-table-column label="退料数量" prop="returnQty" width="120" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.returnQty"
                :min="0"
                :max="scope.row.availableQty"
                :precision="2"
                size="small"
                style="width: 100%;"
              />
            </template>
          </el-table-column>
          <el-table-column label="批次号" prop="batchNo" width="120" align="center">
            <template slot-scope="scope">
              <el-select v-model="scope.row.batchNo" placeholder="选择批次" style="width: 100%;">
                <el-option
                  v-for="batch in scope.row.batchList || []"
                  :key="batch.batchNo"
                  :label="batch.batchNo"
                  :value="batch.batchNo"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="退料原因" prop="itemReason" width="150" align="center">
            <template slot-scope="scope">
              <el-select v-model="scope.row.itemReason" placeholder="选择原因" size="small" style="width: 100%;">
                <el-option label="剩余未用" value="unused" />
                <el-option label="质量问题" value="quality" />
                <el-option label="规格不符" value="spec" />
                <el-option label="其他" value="other" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="150" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="备注" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center" fixed="right">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="handleDeleteMaterial(scope.$index)"
                style="color: #F56C6C;"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 汇总信息 -->
      <div class="summary-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="summary-item">
              <label>物料种类：</label>
              <span>{{ materialList.length }} 种</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="summary-item">
              <label>总已领用数量：</label>
              <span>{{ totalUsedQty }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="summary-item">
              <label>总退料数量：</label>
              <span>{{ totalReturnQty }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="summary-item">
              <label>状态：</label>
              <span :class="statusClass">{{ statusText }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 添加物料对话框 -->
    <el-dialog title="选择退料物料" :visible.sync="materialDialogVisible" width="80%">
      <el-table :data="usedMaterials" @selection-change="handleMaterialSelection" style="width: 100%;">
        <el-table-column type="selection" width="55" />
        <el-table-column label="物料编号" prop="materialCode" width="150" />
        <el-table-column label="物料名称" prop="materialName" width="200" />
        <el-table-column label="规格型号" prop="specification" width="150" />
        <el-table-column label="单位" prop="unit" width="80" />
        <el-table-column label="已领用数量" prop="usedQty" width="100" />
        <el-table-column label="可退料数量" prop="availableQty" width="100" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="materialDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmMaterial">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getWarehouseList,
  getUsedMaterials,
  getReturnableQty,
  generateReturnCode,
  submitReturn,
  saveReturnDraft
} from "@/api/ck/material";

export default {
  name: "MaterialReturn",
  data() {
    return {
      // 任务信息
      taskInfo: {
        taskId: null,
        taskCode: '',
        workOrderCode: ''
      },
      // 当前时间
      currentTime: '',
      // 退料表单
      returnForm: {
        returnCode: '',
        returnType: 'production',
        returnDate: new Date(),
        warehouseId: null,
        returner: '',
        department: '',
        returnReason: '',
        remark: ''
      },
      // 表单验证规则
      formRules: {
        returnType: [
          { required: true, message: '请选择退料类型', trigger: 'change' }
        ],
        returnDate: [
          { required: true, message: '请选择退料日期', trigger: 'change' }
        ],
        warehouseId: [
          { required: true, message: '请选择退料仓库', trigger: 'change' }
        ],
        returner: [
          { required: true, message: '请输入退料人', trigger: 'blur' }
        ],
        returnReason: [
          { required: true, message: '请选择退料原因', trigger: 'change' }
        ]
      },
      // 仓库列表
      warehouseList: [],
      // 物料列表
      materialList: [],
      // 已使用的物料
      usedMaterials: [],
      // 选中的物料
      selectedMaterials: [],
      // 对话框显示状态
      materialDialogVisible: false,
      // 提交状态
      submitting: false
    };
  },
  computed: {
    // 总已领用数量
    totalUsedQty() {
      return this.materialList.reduce((total, item) => total + (item.usedQty || 0), 0);
    },
    // 总退料数量
    totalReturnQty() {
      return this.materialList.reduce((total, item) => total + (item.returnQty || 0), 0);
    },
    // 状态样式
    statusClass() {
      if (this.totalReturnQty === 0) return 'status-draft';
      if (this.totalReturnQty < this.totalUsedQty) return 'status-partial';
      return 'status-complete';
    },
    // 状态文本
    statusText() {
      if (this.totalReturnQty === 0) return '草稿';
      if (this.totalReturnQty < this.totalUsedQty) return '部分退料';
      return '全部退料';
    }
  },
  created() {
    this.initData();
    this.generateReturnCode();
    this.getCurrentTime();
    this.getWarehouseList();
    this.getUsedMaterials();
  },
  methods: {
    // 初始化数据
    initData() {
      // 从路由参数获取任务信息
      this.taskInfo.taskId = this.$route.query.taskId;
      this.taskInfo.taskCode = this.$route.query.taskCode;
      this.taskInfo.workOrderCode = this.$route.query.workOrderCode;
      
      // 设置默认值
      this.returnForm.returner = this.$store.state.user.name || '';
      this.returnForm.department = '生产部门';
    },
    
    // 生成退料单号
    generateReturnCode() {
      const now = new Date();
      const dateStr = now.getFullYear().toString() + 
                     (now.getMonth() + 1).toString().padStart(2, '0') + 
                     now.getDate().toString().padStart(2, '0');
      const timeStr = now.getHours().toString().padStart(2, '0') + 
                     now.getMinutes().toString().padStart(2, '0') + 
                     now.getSeconds().toString().padStart(2, '0');
      this.returnForm.returnCode = `RET${dateStr}${timeStr}`;
    },
    
    // 获取当前时间
    getCurrentTime() {
      const now = new Date();
      this.currentTime = now.getFullYear() + '-' + 
                        (now.getMonth() + 1).toString().padStart(2, '0') + '-' + 
                        now.getDate().toString().padStart(2, '0') + ' ' + 
                        now.getHours().toString().padStart(2, '0') + ':' + 
                        now.getMinutes().toString().padStart(2, '0') + ':' + 
                        now.getSeconds().toString().padStart(2, '0');
    },
    
    // 获取仓库列表
    getWarehouseList() {
      // 模拟数据，实际应调用API
      this.warehouseList = [
        { warehouseId: 1, warehouseName: '原材料仓库' },
        { warehouseId: 2, warehouseName: '半成品仓库' },
        { warehouseId: 3, warehouseName: '成品仓库' }
      ];
    },
    
    // 获取已使用的物料
    getUsedMaterials() {
      // 模拟数据，实际应调用API获取该任务已领用的物料
      this.usedMaterials = [
        {
          materialCode: 'WL001',
          materialName: '钢材A',
          specification: '20*50*30',
          unit: 'kg',
          usedQty: 80,
          availableQty: 20,
          batchList: [
            { batchNo: 'B20250718001', qty: 15 },
            { batchNo: 'B20250718002', qty: 5 }
          ]
        },
        {
          materialCode: 'WL002',
          materialName: '钢材B',
          specification: '30*60*40',
          unit: 'kg',
          usedQty: 60,
          availableQty: 20,
          batchList: [
            { batchNo: 'B20250718003', qty: 20 }
          ]
        }
      ];
    },
    
    // 仓库变更处理
    handleWarehouseChange(warehouseId) {
      // 重新获取该仓库的物料信息
      this.getUsedMaterials();
    },
    
    // 添加物料
    handleAddMaterial() {
      this.materialDialogVisible = true;
    },
    
    // 物料选择变更
    handleMaterialSelection(selection) {
      this.selectedMaterials = selection;
    },
    
    // 确认添加物料
    handleConfirmMaterial() {
      this.selectedMaterials.forEach(material => {
        // 检查是否已存在
        const exists = this.materialList.find(item => item.materialCode === material.materialCode);
        if (!exists) {
          this.materialList.push({
            ...material,
            returnQty: 0,
            batchNo: '',
            itemReason: '',
            remark: ''
          });
        }
      });
      this.materialDialogVisible = false;
      this.selectedMaterials = [];
    },
    
    // 物料变更处理
    handleMaterialChange(index, row) {
      const material = this.usedMaterials.find(item => item.materialCode === row.materialCode);
      if (material) {
        this.$set(this.materialList, index, {
          ...material,
          returnQty: row.returnQty || 0,
          batchNo: row.batchNo || '',
          itemReason: row.itemReason || '',
          remark: row.remark || ''
        });
      }
    },
    
    // 删除物料
    handleDeleteMaterial(index) {
      this.materialList.splice(index, 1);
    },
    
    // 提交退料
    handleSubmit() {
      this.$refs.returnForm.validate(valid => {
        if (valid) {
          if (this.materialList.length === 0) {
            this.$message.warning('请至少添加一种退料物料');
            return;
          }
          
          // 检查是否有物料未填写退料数量
          const invalidItems = this.materialList.filter(item => !item.returnQty || item.returnQty <= 0);
          if (invalidItems.length > 0) {
            this.$message.warning('请填写有效的退料数量');
            return;
          }
          
          this.submitting = true;
          
          // 构造提交数据
          const submitData = {
            ...this.returnForm,
            taskId: this.taskInfo.taskId,
            materialList: this.materialList
          };
          
          // 模拟API调用
          setTimeout(() => {
            this.submitting = false;
            this.$message.success('退料单提交成功');
            this.goBack();
          }, 2000);
        }
      });
    },
    
    // 保存草稿
    handleSaveDraft() {
      this.$message.success('草稿保存成功');
    },
    
    // 重置表单
    handleReset() {
      this.$refs.returnForm.resetFields();
      this.materialList = [];
      this.generateReturnCode();
    },
    
    // 返回
    goBack() {
      this.$router.go(-1);
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  margin: 0 0 10px 0;
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.task-info {
  font-size: 14px;
  color: #606266;
}

.content-card {
  min-height: 600px;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.content-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.form-actions {
  display: flex;
  gap: 10px;
}

.material-section {
  margin-top: 30px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-header h4 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.summary-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.summary-item {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.summary-item label {
  font-weight: bold;
  color: #606266;
  margin-right: 5px;
}

.summary-item span {
  color: #303133;
}

.status-draft {
  color: #909399;
}

.status-partial {
  color: #e6a23c;
}

.status-complete {
  color: #67c23a;
}

.dialog-footer {
  text-align: right;
}

/* 表格样式优化 */
.el-table {
  font-size: 14px;
}

.el-table th {
  background-color: #fafafa;
  color: #606266;
  font-weight: bold;
}

/* 表单样式优化 */
.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__label {
  color: #606266;
  font-weight: bold;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    align-items: flex-start;
  }

  .header-right {
    margin-top: 15px;
  }

  .content-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .form-actions {
    margin-top: 15px;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .section-header .el-button {
    margin-top: 10px;
  }
}
</style>
